<?php
namespace Modules\Product\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Product\Entities\Product;
use Modules\Activity\Entities\Seckill\Activity as Seckill;

use Modules\Asset\Entities\PackageSku;

use \Modules\Core\Entities\SubscribeRecord;

use Validator;
use ThrowException;
use DB;
use Auth;

class ProductController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['order_by'] = [
            'list_weight' => 'desc'
        ];

        $options['scopes'] = ['onStock'];

        // $options['per_page'] = 100;

        $options['with'] = ['image_tag'];

        // 如果是抖音平台
        if (Auth::platformType() === 'byte_dance') {
            array_push($options['scopes'], 'onlyScorePrice');
        }

        $options['only'] = [
            'id',
            'uuid',
            'title',
            'thumb',
            'number',
            'money_price',
            'score_price',
            'discount_money_price',
            'discount_score_price',
            'tags',
            'stock',
            'is_presell',
            'image_tag' => [
                // 'title',
                'image',
                'location'
            ],
        ];
        
        $list = Product::getList($options);
        return $list->generateListResponse();
    }

    public function show(Request $req, $uuid)
    {
	    	
	if (is_numeric($uuid)) {
            $builder = Product::where('id', intVal($uuid));
        }
        else {
            $builder = Product::where('uuid', $uuid); 
        }

        $item = Product::getEntity([
            'builder' => $builder,
            'with' => [
                // 'groupon.skus',
                'ext',
                'skus.chip',
                'group_prices.group',
                'image_tag'
            ]
        ]);

        $item->isOnOffer() || ThrowException::Conflict('商品已下架', 6001);

        // 检查预售状态
        if ($item->is_presell) {
            if (strtotime($item->presell_date) <= time()) {
                $item->is_presell = 0; 
                $item->update([
                    'is_presell' => 0
                ]);
            }
        }

        // 如果有置换活动
        if ($req->input('mode') === 'exchange') {
            $user = Auth::requireLoginUser();
            // 准备要兑换的仓库物品
            $packageSkus = PackageSku::status('pending')->where('user_id', $user->id)->whereIn('id', $req->input('package_sku_ids'))->get();
            // 计算这些物品可抵扣的人民币及积分数额
            list($money, $score) = PackageSku::calcExchangeInfoForList($packageSkus);

            $item->skus->each(function ($sku) use ($money, $score) {
                $sku->pay_money_price = subtractOrZero($sku->money_price, $money);
                $sku->pay_score_price = subtractOrZero($sku->score_price, $score); 
            });
        }

        $info = $item->getInfo([
            'id',
            'uuid',
            'title',
            'sub_title',
            'thumb',
            'poster',
            'tags',
            'number',
            'carriage',
            'carriage_type',
            'money_price',
            'score_price',
            'discount_money_price',
            'discount_score_price',
            'is_shoe_stock',
            'is_show_sales',
            'is_presell',
            'order_reward',
            'presell_mode',
            'presell_date',
            'cover_chip_status',
            'stock',
            'ext',
            'group_prices',
            'skus' => [
                '*' => [
                    'id',
                    'uuid',
                    'number',
                    'attrs',
                    'thumb',
                    'money_price',
                    'line_money_price',
                    'score_price',
                    'line_score_price',
                    'pay_money_price',    // 置换时需要补的人民币差价
                    'pay_score_price',    // 置换时需要补的积分差价
                    'stock',
                    'weight',
                    'sales',
                    'cover_chip_status',
                    'cover_chip_total',
                    'cover_chip_id',
                    'chip',
                    'status'
                ]
            ],
            'group_prices' => [
                '*' => [
                    'id',
                    'uuid',
                    'gorup_id',
                    'title',
                    'money_price',
                    'score_price',
                    'group' => [
                        'id',
                        'uuid',
                        'title'
                    ]
                ]
            ],
            'image_tag' => [
                // 'title',
                'image',
                'location'
            ],
        ]);

        // 如果有对应秒杀活动
        if ($req->input('seckill_id')) {
            $seckill = Seckill::getEntity([
                'id' => $req->seckill_id
            ], false);

            // 秒杀是否包括此活动
            if ($seckill->isIncludeNode($item)) {
                $info['seckill'] = $seckill->getSeckillInfo();

                // 活动进行中，替换活动价
                if ($seckill->union_status == 'working') {
                    foreach ($info['skus'] as $key => $sku) {
                        $info['skus'][$key]['discount_money_price'] = $seckill->discount_money_price;
                        $info['skus'][$key]['discount_score_price'] = $seckill->discount_score_price;
                    }
                }
            }
        }

        // 是否有碎片兑换活动
        if ($item->cover_chip_status) {
            foreach ($item->skus as $sku) {
                if ($sku->cover_chip_status && $sku->chip) {
                    $info['cover_chip'] = [
                        'chip' => [
                            'title' => $sku->chip->title
                        ],
                        'total' => $sku->cover_chip_total
                    ];
                }
            }
        }

        // 是否已订阅过
        $info['is_subscribed'] = 0;
        if ($item->is_presell && Auth::user()) {
            $record = SubscribeRecord::where([
                'target_uuid' => $item->uuid,
                'message_type' => 'presell_start',
                'user_id' => Auth::user()->id,
                'status' => 0
            ])->first();

            if ($record) {
                $info['is_subscribed'] = 1;
            }
        }

       	// $info['skus'][0]['discount_money_price'] = 1;
       	// $info['skus'][0]['discount_score_price'] = 10;

       	// $info['discount_money_price'] = 1;
       	// $info['discount_score_price'] = 10;

        // 团购价
        // if ($item->groupon) {
        //     $info['selling_price'] = $item->groupon->price;
        // }

        return [
            'info' => $info
        ];
    }
}
